package com.yc.web.controller.common;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yc.common.annotation.Log;
import com.yc.common.annotation.RateLimiter;
import com.yc.common.enums.OperationType;
import com.yc.common.core.domain.AjaxResult;
import com.yc.common.constant.Constants;
import com.yc.framework.web.domain.TokenInfo;
import com.yc.framework.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.yc.common.utils.WebUtil;
import com.yc.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;


@Api(tags = "令牌管理")
@RestController
public class SysUserTokenController {

    @Autowired
    private TokenService tokenService;

    /**
     * 验证并刷新令牌
     * 前端每25分钟调用一次该接口
     * 使用刷新令牌验证，有效时创建新的访问令牌，继续保留原刷新令牌
     */
    @Log(module = "令牌管理", type = OperationType.QUERY, description = "获取最新访问令牌")
    @RateLimiter(permitsPerSecond = 5.0, message = "Token 请求过于频繁，请稍后重试。")
    @ApiOperation("获取最新访问令牌")
    @GetMapping("/getNewAccessToken")
    public AjaxResult validateAndGetNewAccessToken() {

        AjaxResult result = AjaxResult.success("令牌验证成功，已刷新");

        // 从请求头获取刷新令牌 - 使用正确的方法获取
        String refreshToken = WebUtil.getRefreshToken();

        try {
            //获取用户信息
            Claims claims = JwtUtil.parseJWT(refreshToken);
            JSONObject jsonObject = JSON.parseObject(claims.getSubject());
            Long userId = Long.valueOf(jsonObject.getString("uid"));

            // 如果refreshToken已经包含Bearer前缀，先去掉
            if (refreshToken != null && refreshToken.startsWith(Constants.TOKEN_PREFIX)) {
                refreshToken = refreshToken.substring(Constants.TOKEN_PREFIX.length());
            }

            // 刷新Token
            TokenInfo tokenInfo = tokenService.refreshAccessToken(refreshToken);

            // 返回结果
            result.put("userId", userId);
            result.put("tokenInfo", tokenInfo);
            result.put("tokenStatus", "validated");
            return result;
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }
}